import React, { useEffect, useState } from 'react';
import { Table, Button, Modal, Form, Input, InputNumber, message, Alert, Card, Space, Empty } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, LoadingOutlined } from '@ant-design/icons';
import { databaseConfigApi, DatabaseConfig } from '../services/api';

const DatabaseConfigPage: React.FC = () => {
    const [form] = Form.useForm();
    const [data, setData] = useState<DatabaseConfig[]>([]);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editingId, setEditingId] = useState<number | null>(null);
    const [isTestingConnection, setIsTestingConnection] = useState(false);
    const [testConnectionResult, setTestConnectionResult] = useState<{ type: 'success' | 'error' | 'info' | null; message: string | null }>({ type: null, message: null });

    const loadData = async () => {
        try {
            const response = await databaseConfigApi.findAll();
            setData(Array.isArray(response.data.data) ? response.data.data : []);
        } catch (error) {
            message.error('加载数据库配置列表失败');
            console.error('Failed to load database configs:', error);
        }
    };

    useEffect(() => {
        loadData();
    }, []);

    const handleAdd = () => {
        form.resetFields();
        setEditingId(null);
        setTestConnectionResult({ type: null, message: null });
        setIsModalVisible(true);
    };

    const handleEdit = (record: DatabaseConfig) => {
        form.setFieldsValue(record);
        setEditingId(record.id);
        setTestConnectionResult({ type: null, message: null });
        setIsModalVisible(true);
    };

    const handleDelete = async (id: number) => {
        try {
            await databaseConfigApi.delete(id);
            message.success('删除成功');
            loadData();
        } catch (error: any) {
            const errorMsg = error.response?.data?.message || error.message || '删除失败';
            message.error(errorMsg);
            console.error('Failed to delete config:', error);
        }
    };

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            if (editingId !== null) {
                await databaseConfigApi.update(editingId, values);
                message.success('更新成功');
            } else {
                await databaseConfigApi.save(values);
                message.success('添加成功');
            }
            setIsModalVisible(false);
            loadData();
        } catch (error: any) {
            const errorMsg = error.response?.data?.message || error.message || '操作失败，请检查表单信息。';
            message.error(errorMsg);
            console.error('Submit failed:', error);
        }
    };

    const handleTestConnection = async () => {
        try {
            const values = await form.validateFields();
            setIsTestingConnection(true);
            setTestConnectionResult({ type: 'info', message: '正在测试连接...' });
            const response = await databaseConfigApi.testConnection(values); 
            if (response.data.code === 200 && response.data.data === true) {
                const successMsg = response.data.message || '数据库连接成功！';
                message.success(successMsg);
                setTestConnectionResult({ type: 'success', message: successMsg });
            } else {
                const errorDetail = response.data.message || '数据库连接失败，请检查配置信息。';
                message.error(errorDetail);
                setTestConnectionResult({ type: 'error', message: errorDetail });
            }
        } catch (error: any) {
            let errorMsg = '连接测试失败，请检查配置或网络。';
            if (error.response && error.response.data && error.response.data.message) {
                errorMsg = error.response.data.message;
            } else if (error.message && error.message.includes("Network Error")) {
                 errorMsg = '网络错误，无法连接到服务器进行测试。';
            } else if (error.message) {
                errorMsg = error.message;
            }
            message.error(errorMsg);
            setTestConnectionResult({ type: 'error', message: errorMsg });
            console.error("Test connection error:", error);
        } finally {
            setIsTestingConnection(false);
        }
    };

    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '主机',
            dataIndex: 'host',
            key: 'host',
        },
        {
            title: '端口',
            dataIndex: 'port',
            key: 'port',
            align: 'right' as const,
        },
        {
            title: '数据库名',
            dataIndex: 'databaseName',
            key: 'databaseName',
        },
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: DatabaseConfig) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button
                        type="link"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => {
                            Modal.confirm({
                                title: '确认删除',
                                content: `确定要删除配置 \"${record.name}\" 吗？`,
                                okText: '删除',
                                okType: 'danger',
                                cancelText: '取消',
                                onOk: () => handleDelete(record.id),
                            });
                        }}
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    return (
        <Card title="数据库连接配置管理">
            <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
                style={{ marginBottom: 16 }}
            >
                添加配置
            </Button>
            <Table 
                columns={columns} 
                dataSource={data} 
                rowKey="id" 
                loading={!data}
                locale={{
                    emptyText: (
                        <Empty
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                            description={(
                                <span>
                                    暂无数据库配置，快去 <Button type="link" onClick={handleAdd} style={{ padding: 0 }}>添加一个</Button> 吧！
                                </span>
                            )}
                        />
                    )
                }}
            />

            <Modal
                title={editingId ? '编辑配置' : '添加配置'}
                open={isModalVisible}
                onCancel={() => {
                    setIsModalVisible(false);
                    setTestConnectionResult({ type: null, message: null });
                }}
                destroyOnClose
                footer={[
                    <Button key="cancel" onClick={() => {
                        setIsModalVisible(false);
                        setTestConnectionResult({ type: null, message: null });
                    }}>
                        取消
                    </Button>,
                    <Button 
                        key="test" 
                        onClick={handleTestConnection} 
                        loading={isTestingConnection} 
                        icon={isTestingConnection ? <LoadingOutlined /> : null}
                    >
                        测试连接
                    </Button>,
                    <Button key="submit" type="primary" onClick={handleSubmit}>
                        确定
                    </Button>,
                ]}
            >
                {testConnectionResult && testConnectionResult.type && testConnectionResult.message && (
                    <Alert 
                        message={testConnectionResult.message} 
                        type={testConnectionResult.type} 
                        showIcon 
                        style={{ marginBottom: 16 }} 
                        closable
                        onClose={() => setTestConnectionResult({ type: null, message: null })}
                    />
                )}
                <Form form={form} layout="vertical" name="dbConfigForm">
                    <Form.Item
                        name="name"
                        label="名称"
                        rules={[{ required: true, message: '请输入名称' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="host"
                        label="主机"
                        rules={[{ required: true, message: '请输入主机' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="port"
                        label="端口"
                        rules={[{ required: true, message: '请输入端口' }]}
                    >
                        <InputNumber style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item
                        name="databaseName"
                        label="数据库名"
                        rules={[{ required: true, message: '请输入数据库名' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="username"
                        label="用户名"
                        rules={[{ required: true, message: '请输入用户名' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        label="密码"
                        rules={[{ required: true, message: '请输入密码' }]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item name="remark" label="备注">
                        <Input.TextArea />
                    </Form.Item>
                </Form>
            </Modal>
        </Card>
    );
};

export default DatabaseConfigPage; 